package com.qb.devtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.List;

import Adapter.SwitchAdapter;
import MyFragment.Fragment2Screen;
import MyFragment.FragmentLed8;
import MyFragment.FragmentMedia;
import MyFragment.FragmentBluetooth;
import MyFragment.FragmentCashbox;
import MyFragment.FragmentDevice;
import MyFragment.FragmentNetwork;
import MyFragment.FragmentPrinter;
import MyFragment.FragmentScan;
import receiver.PowerReceiver;
import utils.DevInfoUtil;
import utils.MyUtil;
import utils.SystemPropertiesReflection;

public class MainActivity extends AppCompatActivity {

    Context ctx;
    public static MainActivity mActivity;
    final private FragmentManager fragmentManager = getSupportFragmentManager();
    public SharedPreferences SP;
    JSONArray switchData;
    Dialog loading;
    // 注册关机重启广播
    PowerReceiver mPowerReceiver = null;
    private RecyclerView rvSwitch;
    private FragmentDevice fDevice;
    private FragmentMedia fMedia;
    private FragmentNetwork fNetwork;
    private FragmentBluetooth fBluetooth;
    private FragmentScan fScan;
    private FragmentPrinter fPrinter;
    private FragmentCashbox fCashbox;
    private FragmentLed8 fLed8;
    private Fragment2Screen f2Screen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ctx = MainActivity.this;
        mActivity = this;
        RegisterBroadCastReceiver();

        if (!hasUsageStatsPermission()) {
            requestUsageStatsPermission();
        } else {
            getUsageStats();
        }

        SP = getSharedPreferences("dev_test_setting", this.MODE_PRIVATE);
        SharedPreferences.Editor edit = SP.edit();
        edit.putString("baseUrl","https://www.androidgmt.com/manager");
        edit.apply();

        // RecyclerView
        rvSwitch = findViewById(R.id.rv_switch);
        switchInit();

        // Fragment
        fDevice = new FragmentDevice();
        fMedia = new FragmentMedia();
        fNetwork = new FragmentNetwork();
        fBluetooth = new FragmentBluetooth();
        fScan = new FragmentScan();
        fPrinter = new FragmentPrinter();
        fCashbox = new FragmentCashbox();
        fLed8 = new FragmentLed8();
        f2Screen = new Fragment2Screen();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fDevice);
        fragmentTransaction.commit();

        new Handler().postDelayed(()-> {
            //login();
        },1);

    }

    public void switchInit() {
        String[] switchArray = {
                "设备信息",
                "网络",
                "蓝牙",
                "多媒体",
                "扫码设备",
                "打印机",
                "钱箱",
//                "LED客显",
                "双屏异显",
        };
        JSONObject o;
        try {
            switchData = new JSONArray();
            for (int i=0;i<switchArray.length;i++) {
                o = new JSONObject();
                int icon = R.drawable.ic_baseline_info_24;
                if (switchArray[i].equals("设备信息")) icon = R.drawable.ic_baseline_info_24;
                if (switchArray[i].equals("网络")) icon = R.drawable.ic_baseline_language_24;
                if (switchArray[i].equals("蓝牙")) icon = R.drawable.ic_baseline_bluetooth_24;
                if (switchArray[i].equals("多媒体")) icon = R.drawable.ic_baseline_video_library_24;
                if (switchArray[i].equals("扫码设备")) icon = R.drawable.ic_baseline_qr_code_scanner_24;
                if (switchArray[i].equals("打印机")) icon = R.drawable.ic_baseline_print_24;
                if (switchArray[i].equals("钱箱")) icon = R.drawable.ic_baseline_inbox_24;
                if (switchArray[i].equals("LED客显")) icon = R.drawable.ic_baseline_calendar_view_day_24;
                if (switchArray[i].equals("双屏异显")) icon = R.drawable.ic_baseline_filter_24;
                o.put("icon",icon);
                o.put("label",switchArray[i]);
                switchData.put(o);
            }
            initAdapter();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(ctx, "项目列表获取失败 "+e.getMessage(), Toast.LENGTH_SHORT);
        }
    }

    private void initAdapter() {
        LinearLayoutManager switchLLM = new LinearLayoutManager(this);
        switchLLM.setOrientation(LinearLayoutManager.VERTICAL);
        rvSwitch.setLayoutManager(switchLLM);
        SwitchAdapter switchAdapter = new SwitchAdapter(this, switchData);
        rvSwitch.setAdapter(switchAdapter);

        switchAdapter.setOnItemClickListener(new SwitchAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                try {
                    //Toast.makeText(ctx, "#"+position, Toast.LENGTH_SHORT).show();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    if (position==0) fragmentTransaction.replace(R.id.fragment_container, fDevice);
                    else if (position==1) {
                        getUsageStats();
                        fragmentTransaction.replace(R.id.fragment_container, fNetwork);
                    }
                    else if (position==2) fragmentTransaction.replace(R.id.fragment_container, fBluetooth);
                    else if (position==3) fragmentTransaction.replace(R.id.fragment_container, fMedia);
                    else if (position==4) fragmentTransaction.replace(R.id.fragment_container, fScan);
                    else if (position==5) fragmentTransaction.replace(R.id.fragment_container, fPrinter);
                    else if (position==6) fragmentTransaction.replace(R.id.fragment_container, fCashbox);
//                    else if (position==7) fragmentTransaction.replace(R.id.fragment_container, fLed8);
                    else if (position==7) fragmentTransaction.replace(R.id.fragment_container, f2Screen);
                    else fragmentTransaction.replace(R.id.fragment_container, fDevice);
                    fragmentTransaction.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void RegisterBroadCastReceiver(){
        mPowerReceiver = new PowerReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.ACTION_SHUTDOWN");
        intentFilter.addAction("android.intent.action.REBOOT");
        registerReceiver(mPowerReceiver,intentFilter);
    }

    private boolean hasUsageStatsPermission() {
        UsageStatsManager usm = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        calendar.add(Calendar.YEAR, -1);
        List<UsageStats> queryUsageStats = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, calendar.getTimeInMillis(), now);

        return queryUsageStats != null && !queryUsageStats.isEmpty();
    }

    private void requestUsageStatsPermission() {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        startActivity(intent);
    }

    private void getUsageStats() {
        UsageStatsManager usm = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();
        calendar.add(Calendar.YEAR, -1);
        List<UsageStats> queryUsageStats = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, calendar.getTimeInMillis(), now);

        if (queryUsageStats != null) {
//            for (UsageStats usageStats : queryUsageStats) {
//                MyUtil.showLog("getUsageStats", "Pkg: " + usageStats.getPackageName() +  "\t" + "ForegroundTime: " + usageStats.getTotalTimeInForeground());
//            }
        }
    }

}